//
//  SudokuViewController.m
//  Sudoku
//
//  Created by iMac-hxsd on 12-2-6.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "SudokuViewController.h"
#import "Constant.h"
#import "SudokuUtil.h"
#import <QuartzCore/QuartzCore.h>

@implementation SudokuViewController

@synthesize menuViewControl,activedButton, lastActivedButton;
@synthesize activedButtonTag, isPosibleValueMode;
@synthesize scrollView = _scrollView;
@synthesize sudokuTable = _sudokuTable;
@synthesize sudokuTableCorrect = _sudokuTableCorrect;
@synthesize doNotEditNumButtons = _doNotEditNumButtons;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        // Custom initialization
    }
    return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self menuView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Menu View
// 菜单视图
- (void) menuView 
{
    menuViewControl = [[UIControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
    menuViewControl.backgroundColor = [UIColor blackColor];
    menuViewControl.alpha = 0.9f;
    
    UIButton *gameStart = [UIButton buttonWithType:UIButtonTypeCustom];
    gameStart.frame = CGRectMake(120.0f, 200.0f, 90.0f, 35.0f);
    [gameStart setTitle:@"开始游戏" forState:0];
    [gameStart addTarget:self action:@selector(playGame) forControlEvents:(UIControlEventTouchDown)];
    [menuViewControl addSubview:gameStart];
    [self.view addSubview:menuViewControl];
}

// 开始游戏
- (void) playGame
{
    menuViewControl.alpha = 0.0f;
    
    [self sudokuInit];
}

// 完成游戏
- (void) completeGame 
{
    BOOL correct = YES;
    for (NSString *pos in [sudokuTable allKeys])
    {
        NSInteger valueCorrect = [[sudokuTableCorrect valueForKey:pos] intValue];
        NSInteger value = [[sudokuTable valueForKey:pos] intValue];
        if(valueCorrect != value)
        {
            UIButton *b = [[self view] viewWithTag:[pos intValue]];
            [b setTitleColor:[UIColor redColor] forState:0];
            correct = NO;
        }
    }

    if (correct) 
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"恭喜您！"
        message:@"太棒了，完全正确"
        delegate:self 
        cancelButtonTitle:@"OK" 
        otherButtonTitles:nil, nil];

        [alertView show];   
    }
}

#pragma mark - Sudoku Button Methods
// 初始化数独
- (void) sudokuInit 
{
	sudokuTableCorrect = [SudokuUtil makeSudoku];
	sudokuTable = [SudokuUtil makeEmptyCell:sudokuTableCorrect forLevel:30];
	// 浅拷贝，doNotEditNumButtons 中的值是不可修改的
	doNotEditNumButtons = [sudokuTable mutableCopy];
	
    int cellWidth = kButtonWidth;
    int cellHeight = kButtonHeight;
    int xSta = kSudokuStartX - cellWidth;
    int ySta = kSudokuStartY - cellHeight;
    for (int i = 1; i <= 9; i++) 
	{
        xSta = xSta + cellWidth;
        for (int j = 1 ; j <= 9; j++) 
		{
            ySta = ySta + cellHeight;
            CGRect pos = CGRectMake(xSta, ySta, cellWidth, cellHeight);
            UIButton *b = [SudokuUtil createSudokuButtonForView:self atPos:pos 
														withTag: j * 10 + i forAction:@selector(numButtonPressed:)];
			// 根据位置获取数独表格背景图片
			NSString *picName  = [SudokuUtil sudokuButtonBg:j y:i];
            [b setBackgroundImage:[[UIImage imageNamed:picName] stretchableImageWithLeftCapWidth:0 topCapHeight:0]  forState:0];
			
			NSString *rowcol = [NSString stringWithFormat:@"%d%d",j,i];
            NSString *value = [sudokuTable valueForKey:rowcol];
            
			if ([[sudokuTable valueForKey:rowcol] isKindOfClass:[NSString class]]) 
			{
				[b setTitle:value forState:0];
			}
			
            [self.scrollView addSubview:b];
        }
        ySta = kSudokuStartY - cellHeight;
    }
}

// 选中按钮
- (IBAction) numButtonPressed : (UIButton *) sender 
{
    // 清除按钮高亮
    [self answerAllButtonClearLight];

    if (activedButton) 
    {
        UIColor *lastActivedButtonColor = activedButton.titleLabel.textColor;
        lastActivedButton = activedButton;
        [[lastActivedButton viewWithTag:kHighlightButtonTag] removeFromSuperview];
        [self.scrollView sendSubviewToBack:lastActivedButton];
        lastActivedButton.titleLabel.textColor = lastActivedButtonColor;
    }
    activedButton = sender;

    int num = sender.tag;    
    activedButtonTag = num;

    if (isPosibleValueMode) 
    {
        [self answerPosibleValueButtonLight:activedButton];
    }
    else
    {
        // 选中按钮的值
        NSInteger value = [[sudokuTable valueForKey:[NSString stringWithFormat:@"%d", sender.tag]] intValue];
        // 如果选中值大于0高亮显示相对应的数字按钮
        [self answerAllButtonClearLight];
        if(value > 0)
        {
            id b = [[self view] viewWithTag:1000 + value];
            [self answerButtonLight:b];
        }
    }


    [self.scrollView bringSubviewToFront:activedButton];
    UIImageView *highlightButton = [[UIImageView alloc] initWithFrame:CGRectMake(1, 1, kButtonWidth - 2, kButtonHeight - 2)];
    [highlightButton.layer setBorderWidth:2.0f];
    [highlightButton.layer setBorderColor:[[UIColor greenColor] CGColor]];
    [highlightButton setTag:kHighlightButtonTag];

    [activedButton addSubview:highlightButton];
    [activedButton bringSubviewToFront:highlightButton];
}

#pragma mark - Selection Button Methods
// 输入数字
- (IBAction) answerButtonPressed : (UIButton *) sender 
{
    NSInteger value = [[doNotEditNumButtons valueForKey:[NSString stringWithFormat:@"%d",activedButton.tag]] intValue];

    if (value == 0) 
    {
        // 清除按钮高亮
        [self answerAllButtonClearLight];

        // 可能数值模式
        if (isPosibleValueMode) 
        {
            [activedButton setTitle:@" " forState:0];
            [sudokuTable setValue:@"0" forKey:[NSString stringWithFormat:@"%d",activedButton.tag]];

            // 获取点击按钮的值，并转换为整型
            int bid = [sender.titleLabel.text intValue];

            // 如果可能值已经存在，删除对应的子视图
            if ([activedButton viewWithTag:activedButton.tag * 10 + bid]) 
            {
                [[activedButton viewWithTag:activedButton.tag * 10 + bid] removeFromSuperview];
            }
            else 
            {
                // 新建一个 UILabel
                UILabel *value = [[UILabel alloc] init];
                // 设置 UILabel 的内容
                value.text = [NSString stringWithFormat:@"%d",bid];
                // 设置 UILabel 的 tag，如 第一行第一列的单元格tag为11，点击数值按钮2，此时 UILabel 的 tag 为 112
                value.tag = activedButton.tag * 10 + bid;
                // 获取 UILabel 在第几行
                int valueRow = bid / 3;
                // 获取 UILabel 在第几列
                int valueCol = bid % 3 - 1;
                // 计算 UILabel 坐标X
                float valueX = kButtonWidth % 10 / 2 + 2;
                // 计算 UILabel 坐标Y
                float valueY = kButtonHeight % 10 / 2;
                // UILabel高度
                int valueHeight = (kButtonHeight / 10) * 10 / 3;
                // UILabel宽度
                int valueWidth = (kButtonWidth / 10) * 10 / 3;
                // 文本大小
                float fontSize = kButtonHeight / 3;

                // 3、6、9这种能整除3的值需要单独处理。
                switch (bid) 
                {
                    case 3:
                        valueRow = 0;
                        valueCol = 2;
                        break;
                    case 6:
                        valueRow = 1;
                        valueCol = 2;
                        break;
                    case 9:
                        valueRow = 2;
                        valueCol = 2;
                        break;
                    default:
                        break;
                }


                // 重新计算坐标X
                valueX = valueX + valueCol * valueWidth;
                // 重新计算坐标Y
                valueY = valueY + valueRow * valueHeight;
                // UILabel的坐标X、Y与宽高。
                value.frame = CGRectMake(valueX, valueY, valueWidth, valueHeight);
                value.font = [UIFont boldSystemFontOfSize:fontSize];
                // 文本颜色为灰色
                value.textColor = [UIColor grayColor];
                // 清除背景色
                value.backgroundColor = [UIColor clearColor];
                // 作为子视图添加到单元格按钮中
                [activedButton addSubview:value];
            }

            // 数字按钮高亮
            [self answerPosibleValueButtonLight:activedButton];
        }
        // 普通模式
        else
        {
            if ([sender.titleLabel.text isEqualToString:activedButton.titleLabel.text]) 
            {
                [activedButton setTitle:@" " forState:0];
                [sudokuTable setValue:@"0" forKey:[NSString stringWithFormat:@"%d",activedButton.tag]];
            }
            else 
            {
                // 铵钮高亮
                [self answerButtonLight:sender];

                [self posibleValueClear:activedButton];

                [activedButton setTitle:sender.titleLabel.text forState:0];
                [activedButton setTitleColor:[UIColor blueColor] forState:0];
                [activedButton.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
                [sudokuTable setValue:sender.titleLabel.text forKey:[NSString stringWithFormat:@"%d",activedButton.tag]];
                
                
                NSLog(@"%@", sudokuTable);
                
                // 检查游戏是否完成
                if ([SudokuUtil isSudokuGameComplete:sudokuTable]) 
                {
                    [self completeGame];
                }
            }
        }
    }
}

// 可能数值模式按钮点击
- (IBAction) posibleValueMedeButtonPressed : (UIButton *) sender 
{
	// 清除按钮高亮
	[self answerAllButtonClearLight];
	
	NSInteger value = [[doNotEditNumButtons valueForKey:[NSString stringWithFormat:@"%d",activedButton.tag]] intValue];
	if (value == 0) 
	{
		[self posibleValueClear:activedButton];
		[sudokuTable setValue:@"0" forKey:[NSString stringWithFormat:@"%d",activedButton.tag]];
	}
	
	
    if (isPosibleValueMode) 
	{
        isPosibleValueMode = NO;
        [sender setBackgroundColor:[UIColor redColor]];
		[sender.layer setBorderColor:[[UIColor clearColor] CGColor]];
        [sender.layer setCornerRadius:0];
    }
    else 
	{
        isPosibleValueMode = YES;
        [sender setBackgroundColor:[UIColor clearColor]];
		[sender.layer setBorderColor:[[UIColor orangeColor] CGColor]];
		[sender.layer setBorderWidth:2.0f];
        [sender.layer setCornerRadius:5];
        [sender.layer setMasksToBounds:YES];
    }
}

// 清空可能数值
- (void) posibleValueClear : (id) sender 
{
	[activedButton setTitle:@" " forState:0];
	
    for (UIView *v in [sender subviews]) 
	{
        if(v.tag / 10 == [sender tag]) 
		{
			[v removeFromSuperview];
		}
    }
}

#pragma mark - Answer Button Light
// 按钮高亮
- (void) answerButtonLight : (UIButton *) sender 
{
	sender.backgroundColor = [UIColor orangeColor];
}

// 可能数值模式数值高亮
- (void) answerPosibleValueButtonLight: (id) sender 
{
    for (UILabel *v in [sender subviews]) 
	{
        if(v.tag / 10 == [sender tag]) 
		{
			id b = [[self view] viewWithTag:1000 + [v.text intValue]];
			[self answerButtonLight:b];
		}
    }
}

// 所有按钮清除高亮
- (void) answerAllButtonClearLight
{
	for (int i = 1001; i <= 1009; i++) 
	{
		id b = [[self view] viewWithTag:i];
		[b setBackgroundColor:[UIColor blackColor]];
	}
}

#pragma mark - Memory
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
@end
